package org.tio.sitexxx.web.server.controller.minip;


import com.alibaba.fastjson.JSON;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.tio.http.common.HttpRequest;
import org.tio.http.server.annotation.RequestPath;
import org.tio.sitexxx.service.model.main.*;
import org.tio.sitexxx.service.service.qj.*;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.web.server.utils.ObjectToMap;
import org.tio.sitexxx.web.server.utils.Wxlogin;
import org.tio.utils.jfinal.P;
import org.tio.utils.resp.Resp;

import java.sql.SQLException;
import java.util.*;

@RequestPath(value = "/users")
public class UserController {
    public static final String db = Const.Db.TIO_SITE_MAIN;
    public UserController() {

    }

    /**
     * 用户登录
     * @param request
     * @return
     * @throws Exception
     */
    @RequestPath(value = "/mplogin")
    public Object mplogin(HttpRequest request) throws Exception {
        Map<String, Object> requestmap = JSON.parseObject(request.getBodyString());
//        System.out.println("requestmap:" + JSON.toJSONString(requestmap));
//        System.out.println(request.getBodyString());
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> query = new HashMap<>();


        JSONObject SessionKeyOpenId = Wxlogin.getSessionKeyOrOpenId((String) requestmap.get("code"));//获取openid
        if (SessionKeyOpenId.get("errcode") != null) {
            resultMap.put("openid", "fail");
            return resultMap;
        }
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");

        query.put("openid", openid);
        //登陆不用缓存
        Member Member1 = MemberService.me.getMemberWithoutCatch(query);
        Map<String, Object> Member2 = new HashMap<>(12);
        //用户未登陆过
        if (Member1 == null) {

            Date date = new Date();
            Calendar curr = Calendar.getInstance();
            curr.set(Calendar.YEAR, curr.get(Calendar.YEAR) + 1);//设置优惠券过期时间
            JSONObject userInfo = Wxlogin.getUserInfo((String) requestmap.get("encryptedData"), sessionKey, (String) requestmap.get("iv"));
            String avatar=userInfo.getString("avatarUrl");
            String gender=userInfo.getString("gender");
            String province=userInfo.getString("province");
            String nickname=userInfo.getString("nickName");
            String city=userInfo.getString("city");
            System.out.println("gender:" + userInfo.getString("gender"));
            Record member = new Record().set("avatar", avatar).set("city", city)
                    .set("province", province).set("openid", userInfo.getString("openId"))
                    .set("gender", gender).set("gold", 20).set("signin_time", date).set("nickname", nickname)
                    .set("createdAt",date).set("updatedAt",date);
            Db.tx(new IAtom() {
                @Override
                public boolean run() throws SQLException {
                    Db.use(db).save("member", "id", member);

                    Record user=new Record().set("id",member.get("id")).set("loginname",openid).set("nick",nickname)
                            .set("status",1).set("createtime",date).set("updatetime",date).set("avatar",avatar)
                            .set("pwd","").set("ipid",0);
                    Db.use(db).save("user",  user);
                    return true;
                }
            });
            Member2.put("avatar", avatar);
            Member2.put("city", userInfo.getString("city"));
            Member2.put("province", userInfo.getString("province"));
            //Member.setNickname(userInfo.getString("nickName"));
            Member2.put("openid", userInfo.getString("openId"));
            Member2.put("gender", userInfo.getString("gender"));
            Member2.put("gold", 20);
            Member2.put("signin_time", new Date());
            Integer id = Integer.valueOf(member.get("id").toString());
            Member2.put("id", id);
            System.out.println("new member:" + Member2);
            Record coupon = new Record().set("usage", "个人形象测试专项优惠券").set("value", 29800).set("type", 11).set("memo", "首次登录自动发放").set("memberId", id)
                    .set("endtime", curr.getTime()).set("createdAt", date).set("updatedAt", date).set("status", 1).set("valid", 1);
            Db.use(db).save("coupon", coupon);

            for (int i = 0; i < 2; i++) {
                coupon = new Record().set("usage", "个人形象测试专项优惠券").set("value", 100).set("type", 12).set("memo", "首次登录自动发放").set("memberId", id)
                        .set("endtime", curr.getTime()).set("createdAt", date).set("updatedAt", date).set("status", 1).set("valid", 1);
                Db.use(db).save("coupon", coupon);

                coupon = new Record().set("usage", "个人形象测试专项优惠券").set("value", 500).set("type", 12).set("memo", "首次登录自动发放").set("memberId", id)
                        .set("endtime", curr.getTime()).set("createdAt", date).set("updatedAt", date).set("status", 1).set("valid", 1);
                Db.use(db).save("coupon", coupon);

                coupon = new Record().set("usage", "个人形象测试专项优惠券").set("value", 100).set("type", 12).set("memo", "首次登录自动发放").set("memberId", id)
                        .set("endtime", curr.getTime()).set("createdAt", date).set("updatedAt", date).set("status", 1).set("valid", 1);
                Db.use(db).save("coupon", coupon);
            }

            Member2.put("isFirst", true);
            if (requestmap.get("scene") != null) {//是否是扫描二维码登陆
                try{
                    query.put("mobile", requestmap.get("scene"));
                    query.put("openid", null);
                    //为二维码推广者增加一天记录
                    Promoter Promoter = PromoterService.me.findPromoter((String) requestmap.get("scene"));
                    Promotion Promotion = new Promotion();
                    Promotion.setOpenid(openid);
                    Promotion.setPromoterId(Promoter.getId());
                    Promotion.setCreatedAt(new Date());
                    Promotion.setUpdatedAt(new Date());
                    try {
                        PromotionService.me.save(Promotion);
                    } catch (Exception e) {
                        System.out.println("PromotionService save error msg:"+e.getMessage());
                    }
                }catch (Exception e){
                    System.out.println("promoter  error msg:"+e.getMessage());
                }

            }
            return Member2;//未登录用户
        }
        System.out.println("member1:"+Member1);
        return Member1;//曾登陆用户


    }

    /**
     *金币换优惠卷
     */
    @RequestPath(value = "/gold/exchange")

    public Map<String, Object> exchange(HttpRequest request) {
        System.out.println("gold exchange called");
        Map<String, Object> body = JSON.parseObject(request.getBodyString());
        String openid = (String) body.get("openid");
        com.alibaba.fastjson.JSONArray coupon=JSON.parseArray(JSON.toJSONString(body.get("coupon")));
        Map<String, Object> query = new HashMap<>();
        query.put("openid", openid);
        Member Member = MemberService.me.getMember(query);

        Date date = new Date();
        Calendar curr = Calendar.getInstance();
        curr.set(Calendar.YEAR, curr.get(Calendar.YEAR) + 1);//设置优惠券过期时间

        for (int i = 0; i < coupon.size(); i++) {
            JSONObject jsonObject = JSONObject.fromObject(coupon.get(i));
            for (int j = 0; j < (Integer) jsonObject.get("number"); j++) {
                if (Integer.valueOf((String) jsonObject.get("type")) == 11) {

                    Record coupondata = new Record().set("usage", "个人形象测试专项优惠券").set("value", 298000).set("type", 11).set("memo", "金币兑换").set("memberId", Member.getId())
                            .set("endtime", curr.getTime()).set("createdAt", date).set("updatedAt", date).set("status", 1).set("valid", 1);
                    Db.save("coupon", coupondata);
                }
                if (Integer.valueOf((String) jsonObject.get("type")) == 12) {
                    Record coupondata = new Record().set("usage", "私人电子衣橱专项优惠券").set("value", 100).set("type", 12).set("memo", "金币兑换").set("memberId", Member.getId())
                            .set("endtime", curr.getTime()).set("createdAt", date).set("updatedAt", date).set("status", 1).set("valid", 1);
                    Db.save("coupon", coupondata);
                }
                if (Integer.valueOf((String) jsonObject.get("type")) == 13) {
                    Record coupondata = new Record().set("usage", "咨询抵现优惠券").set("value", 100).set("type", 13).set("memo", "金币兑换").set("memberId", Member.getId())
                            .set("endtime", curr.getTime()).set("createdAt", date).set("updatedAt", date).set("status", 1).set("valid", 1);
                    Db.save("coupon", coupondata);
                }
                Member.setGold(Member.getGold() - (Integer) jsonObject.get("value"));

            }
        }
        MemberService.me.update(Member);
        Map<String, Object> result = new HashMap<>();
        result.put("ok", 0);
        result.put("gold", Member.getGold());
        return result;

    }

    /**
     *有点迷，用户金币这边的逻辑是这样的:
     * 用户每次登陆增加二十金币每到一百自动生成一张衣橱卷 金币换优惠卷的接口如上
     */
    @RequestPath(value = "/gold/number")
    //用户金币
    public Object number(String openid) {
        System.out.println("gold number");
        Map<String, Object> query = new HashMap<>();
        query.put("openid", openid);
        Member Member = MemberService.me.getMember(query);
        if (Member.getGold() == null) {
            Member.setGold(0);
            MemberService.me.update(Member);
        }
        return Member;
    }

    /**
     * 用户提交形象测试结果处理,把用户答案拼成字符串存在数据库中
     */
    @RequestPath(value = "/test_answer")
    public Map<String, Object> test_answer_post(HttpRequest request) {
        System.out.println("called imageTest");
        Map<String, Object> body = JSON.parseObject(request.getBodyString());
        String openid = body.get("openid").toString();
        String test_answer = body.get("test_answer").toString();
        String name = body.get("name").toString();
        String mobile = body.get("mobile").toString();
        String age_scope = body.get("age_scope").toString();
        String profession = body.get("profession").toString();
        Map<String, Object> result = new HashMap<>();

        Map<String, Object> query = new HashMap<>();
        query.put("openid", openid);
        Member Member = MemberService.me.getMember(query);
        Member.setProfession(profession);
        Member.setTestAnswer(test_answer);
        Member.setName(name);
        Member.setMobile(mobile);
        Member.setAgeScope(age_scope);
        Member.setTested("1");
        MemberService.me.update(Member);

        JSONArray array = JSONArray.fromObject(test_answer);
        JSONArray hobbies = new JSONArray();
        JSONArray occasion = new JSONArray();

        for (int i = 7; i < array.size(); i++) {
            hobbies.add(array.getString(i));
        }
        for (int i = 11; i < 12; i++) {
            occasion.add(hobbies.getString(i));
        }

        Imagetesting imagetesting = new Imagetesting();
        imagetesting.setHobbies(hobbies.toString());
        imagetesting.setOccasion(occasion.getString(0));
        imagetesting.setMemberId(Member.getId());
        Date date=new Date();
        imagetesting.setCreatedAt(date);
        imagetesting.setUpdatedAt(date);
        Imagetesting old=Imagetesting.dao.findFirst("select * from imagetesting where memberId=?",Member.getId());
        System.out.println("imgageTesting:"+JSON.toJSONString(old));
        if(old==null){
            ImagetestingService.me.save(imagetesting);
            query.put("type", 11);
            query.put("memberId", Member.getId());
            Coupon Coupon = CouponService.me.getCoupons(query).get(0);
            Coupon.setStatus((short) 3);
            CouponService.me.update(Coupon);
        }
        result.put("ok", 0);
        return result;
    }
    /**
     *
     */
 /*   @RequestPath(value = "/test_answer")
    Map<String, Object> test_answer_get(String openid) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> query = new HashMap<>();
        query.put("openid", openid);
        Member Member = MemberService.me.getMember(query);
        result.put("ok", 0);
        result.put("test_answer", Member.getTestAnswer());
        result.put("tested", Member.getTested());
        return result;
    }*/

    /**
     *
     */
    @RequestPath(value = "/gold/signin")
    //签到
    @SuppressWarnings("deprecation")
    public Map<String, Object> gold_signin(HttpRequest request) {
        System.out.println("gold signin");
        Map<String, Object> body = JSON.parseObject(request.getBodyString());
        String openid = body.get("openid").toString();
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> query = new HashMap<>();
        query.put("openid", openid);
        Member Member = MemberService.me.getMember(query);
        Date today = new Date();
        //第一次登陆或者隔天登陆 算 签到
        if (Member.getSigninTime() == null || Member.getSigninTime().getDate() < today.getDate() || Member.getSigninTime().getMonth() < today.getMonth() || Member.getSigninTime().getYear() < today.getYear()) {
            Member.setSigninTime(today);
            Member.setGold(Member.getGold() + 20);
            MemberService.me.update(Member);
            result.put("ok", 0);
        } else {
            result.put("ok", 3);
        }
        result.put("balance", Member.getBalance());
        result.put("gold", Member.getGold());
        return result;
    }

    /**
     *
     */
    @RequestPath(value = "/userimage")
    //用户画像（用户描述）
    public Object userimage_get(String openid) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> query = new HashMap<>();
        query.put("openid", openid);
        System.out.println(openid);
        Member Member = MemberService.me.getMember(query);
        query.put("memberId", Member.getId());
        Imagetesting Imagetesting = ImagetestingService.me.getImagetesting(query);
        if (Imagetesting == null) {
            resultMap.put("ok", 3);//结果不存在
            return resultMap;
        }

        return Imagetesting;
    }
    @RequestPath(value = "/user/test")
    public Resp user_test(Integer id){
        if(id==null)return Resp.fail("参数错误");
        Map<String,Object>temp=new HashMap<>(2);
        temp.put("id",id);
        Member member=MemberService.me.getMemberWithoutCatch(temp);
        if(member==null){
            return Resp.fail();
        }
        return Resp.ok(member);
    }
}


